package net.rock.eshop.controller.manage;

import net.rock.eshop.config.AppConfig;
import net.rock.eshop.entity.Book;
import net.rock.eshop.exception.InvalidRequestException;
import net.rock.eshop.exception.ServerIOException;
import net.rock.eshop.exception.UnauthorizedOperationException;
import net.rock.eshop.service.BookService;
import net.rock.eshop.utils.AdminChecker;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/api/manage/book")
public class BookManageController {
    @Autowired
    private BookService bookService;
    @Autowired
    private AdminChecker adminChecker;
    @Autowired
    private AppConfig appConfig;

    private String saveImg(MultipartFile img) throws IOException {
        String filename = img.getOriginalFilename();
        if (filename == null) {
            filename = new Date() + ".jpg";
        }
        String[] filenameSplits = filename.split("\\.");
        StringBuilder prefixBuilder = new StringBuilder();

        for (int i = 0; i < filenameSplits.length - 1; i++) {
            prefixBuilder.append(filenameSplits[i]);
            prefixBuilder.append('.');
        }
        prefixBuilder.append(new Date());
        String prefix = DigestUtils.md5Hex(prefixBuilder.toString());
        String suffix = filenameSplits[filenameSplits.length - 1];

        String localFilename = String.format("%s.%s", prefix, suffix);
        String localPath = appConfig.getUploadPath() + localFilename;

        byte[] data = img.getBytes();
        BufferedOutputStream os = new BufferedOutputStream(Files.newOutputStream(Paths.get(localPath)));
        os.write(data);  // 写入图像文件
        os.close();

        return appConfig.getImgPath() + localFilename;
    }

    @PostMapping("/add")
    public void add(
            @CookieValue(value = "sessionID", defaultValue = "") String sessionId,
            @RequestParam("title") String title,
            @RequestParam("author") String author,
            @RequestParam("publisher") String publisher,
            @RequestParam("categoryId") int categoryId,
            @RequestParam("price") double price,
            @RequestParam("img") MultipartFile img
    ) {
        if (!adminChecker.checkAdmin(sessionId)) {
            throw new UnauthorizedOperationException();
        } else {
            try {
                String remotePath = saveImg(img);

                Book book = new Book(
                        0, title, author, publisher, categoryId, price, remotePath
                );

                bookService.add(book);
            } catch (IOException e) {
                throw new ServerIOException(e);
            }
        }
    }

    @PostMapping("/del")
    public void del(@CookieValue("sessionID") String sessionId, @RequestBody Map<String, String> body) {
        if (!adminChecker.checkAdmin(sessionId)) {
            throw new UnauthorizedOperationException();
        } else {
            String id = body.get("id");
            if (id == null) {
                throw new InvalidRequestException();
            } else {
                bookService.del(Integer.parseInt(id));
            }
        }
    }

    @PostMapping("/edit")
    public void edit(
            @CookieValue("sessionID") String sessionId,
            @RequestParam("id") int id,
            @RequestParam("title") String title,
            @RequestParam("author") String author,
            @RequestParam("publisher") String publisher,
            @RequestParam("categoryId") int categoryId,
            @RequestParam("price") double price,
            @RequestParam(value = "img", required = false) MultipartFile img
    ) {
        if (!adminChecker.checkAdmin(sessionId)) {
            throw new UnauthorizedOperationException();
        } else {
            try {
                Book book = bookService.fetchBookById(id);
                book.setTitle(title);
                book.setAuthor(author);
                book.setPublisher(publisher);
                book.setCategoryId(categoryId);
                book.setPrice(price);
                if (img != null) {
                    String remotePath = saveImg(img);
                    book.setImgUrl(remotePath);
                }
                bookService.edit(book);
            } catch (IOException e) {
                throw new ServerIOException(e);
            }
        }
    }
}
